<template>
  <el-drawer :title="dialogTitle" v-model="dialogVisible" size="70%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >

      <el-row>
        <el-col :span="14">
          <el-row>
            <!--            <el-col :span="22">-->
            <!--              <el-form-item label="机构名称" prop="orgName">-->
            <!--                <el-input v-model="formData.orgName" placeholder="请输入机构名称" />-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
            <el-col :span="22">
              <el-form-item label="上级科室">
                <el-tree-select
                  v-model="formData.parentId"
                  :data="deptTree"
                  :default-expanded-keys="[0]"
                  :props="defaultProps"
                  check-strictly
                  node-key="id"
                />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="科室名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入科室名称" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="科室地址" prop="address">
                <el-input v-model="formData.address" placeholder="请输入科室地址" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="链接地址" prop="linkUrl">
                <el-input v-model="formData.linkUrl" placeholder="请输入链接地址" />
              </el-form-item>
            </el-col>
            <!--            <el-col :span="22">-->
            <!--              <el-form-item label="昵称" prop="nickname">-->
            <!--                <el-input v-model="formData.nickname" placeholder="请输入昵称" />-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->

            <el-col :span="22">
              <el-form-item label="his科室编码" prop="hisDeptCode">
                <el-input v-model="formData.hisDeptCode" placeholder="请输入his科室编码" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="his科室名称" prop="hisDeptName">
                <el-input v-model="formData.hisDeptName" placeholder="请输入his科室名称" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="擅长病种" prop="tags">
                <el-input v-model="formData.tags" type="textarea" :rows="2" placeholder="请输入擅长病种" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="提示" prop="tips">
                <el-input type="textarea" v-model="formData.tips" :rows="2" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="通知" prop="notice">
                <el-input type="textarea" v-model="formData.notice" :rows="2" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="描述" prop="description">
                <el-input v-model="formData.description" type="textarea" :rows="2" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="10">
          <el-row>
            <el-col :span="22">
              <el-form-item label="电话" prop="phone">
                <el-input v-model="formData.phone" placeholder="请输入电话" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="工作时段" prop="workRange">
                <el-input v-model="formData.workRange" placeholder="请输入工作时段" />
              </el-form-item>
            </el-col>

            <el-col :span="22">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="formData.remark" :rows="2" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="显示排序" prop="sort">
                <el-input-number v-model="formData.sort" :min="0" clearable controls-position="right" />
              </el-form-item>
            </el-col>
            <el-col :span="22" >
              <el-form-item :label-width="120" label="有效状态" prop="status">
                <template #label>
                  <Tooltip message="开启后内容有效" title="有效状态" />
                </template>
                <el-radio-group v-model="formData.status">
                  <el-radio
                    v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                    :key="dict.value"
                    :label="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="22" >
              <el-form-item :label-width="120" label="发布状态" prop="publish">
                <template #label>
                  <Tooltip message="开启后前端展示内容" title="发布状态" />
                </template>
                <el-radio-group v-model="formData.publish">
                  <el-radio
                    v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                    :key="dict.value"
                    :label="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="22" >
              <el-form-item :label-width="120" label="置顶状态" prop="topping">
                <template #label>
                  <Tooltip message="开启后可展示在首页banner" title="置顶状态" />
                </template>
                <el-radio-group v-model="formData.topping">
                  <el-radio
                    v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                    :key="dict.value"
                    :label="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="22" >
              <el-form-item :label-width="120" label="推荐状态" prop="recommend">
                <template #label>
                  <Tooltip message="开启后可展示在热门推荐" title="推荐状态" />
                </template>
                <el-radio-group v-model="formData.recommend">
                  <el-radio
                    v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                    :key="dict.value"
                    :label="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="22">
              <el-form-item label="图集" prop="pictures">
                <UploadImgs v-model="formData.pictures" />
              </el-form-item>
            </el-col>


<!--            <el-col :span="22">-->
<!--              <el-form-item label="附件" prop="files">-->
<!--                <UploadFile v-model="formData.files" />-->
<!--              </el-form-item>-->
<!--            </el-col>-->
          </el-row>
        </el-col>
        <el-col :span="24">
          <el-form-item label="内容" prop="content">
            <Editor v-model="formData.content" height="250px" />
          </el-form-item>
        </el-col>
      </el-row>


    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { DepartmentApi, DepartmentVO } from '@/api/cms/department'
import { DICT_TYPE, getStrDictOptions, getDictOptions, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import { defaultProps, handleTree } from '@/utils/tree'
import {CompanyApi, CompanyVO} from "@/api/cms/company";

/** 科室信息 表单 */
defineOptions({ name: 'DepartmentForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  parentId: 0,
  name: undefined,
  nickname: undefined,
  coverImg: undefined,
  phone: undefined,
  workRange: undefined,
  tags: undefined,
  address: undefined,
  orgName: undefined,
  hisDeptCode: undefined,
  hisDeptName: undefined,
  linkUrl: undefined,
  tips: undefined,
  notice: undefined,
  description: undefined,
  content: undefined,
  contentFormat: undefined,
  remark: undefined,
  pictures: undefined,
  files: undefined,
  views: undefined,
  publishTime: undefined,
  publish: Number(1),
  topping: Number(1),
  status: Number(1),
  recommend: Number(1),
  sort: Number(0)
})
const formRules = reactive({
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '有效状态不能为空', trigger: 'blur' }],
  publish: [{ required: true, message: '发布状态不能为空', trigger: 'blur' }],
  topping: [{ required: true, message: '置顶状态不能为空', trigger: 'blur' }],
  recommend: [{ required: true, message: '推荐状态不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '顺序不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DepartmentApi.getDepartment(id)
    } finally {
      formLoading.value = false
    }
  }
  // 获得列表
  await getTree()
  await getCompany()
  formData.value.address = formData.value.address || company.value.name
  formData.value.phone = formData.value.phone || company.value.phone
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 获取下拉框[科室]的数据  */
const queryParams = reactive({
  status: CommonStatusEnum.ENABLE
})
const deptTree = ref<Tree[]>([]) // 树形结构
const getTree = async () => {
  deptTree.value = []
  const res = await DepartmentApi.getDepartmentList(queryParams)
  let d: Tree = { id: 0, name: '顶级', children: [] }
  d.children = handleTree(res)
  deptTree.value.push(d)
}

/** 查询医院信息 */
const company = ref<CompanyVO>() // 列表的数据
const getCompany = async () => {
  const data = await CompanyApi.getCompanyPage(queryParams)
  console.table(data)
  if(data.list && data.list.length > 0){
    company.value = data.list[0]
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DepartmentVO
    if (formType.value === 'create') {
      await DepartmentApi.createDepartment(data)
      message.success(t('common.createSuccess'))
    } else {
      await DepartmentApi.updateDepartment(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    parentId: 0,
    name: undefined,
    nickname: undefined,
    coverImg: undefined,
    phone: undefined,
    workRange: undefined,
    tags: undefined,
    address: undefined,
    orgName: undefined,
    hisDeptCode: undefined,
    hisDeptName: undefined,
    linkUrl: undefined,
    tips: undefined,
    notice: undefined,
    description: undefined,
    content: undefined,
    contentFormat: undefined,
    remark: undefined,
    pictures: undefined,
    files: undefined,
    views: undefined,
    publishTime: undefined,
    publish: Number(1),
    topping: Number(1),
    status: Number(1),
    recommend: Number(1),
    sort: Number(0)
  }
  formRef.value?.resetFields()
}
</script>
